<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="平台订单号" prop="platformOrderNo">
        <el-input
          v-model="queryParams.platformOrderNo"
          placeholder="请输入平台订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="平台类型" prop="platformType">
        <el-select v-model="queryParams.platformType" placeholder="请选择平台类型" clearable>
          <el-option
            v-for="dict in dict.type.fiscale_platform_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.fiscale_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报关状态" prop="customsStatus">
        <el-select v-model="queryParams.customsStatus" placeholder="请选择报关状态" clearable>
          <el-option
            v-for="dict in dict.type.fiscale_customs_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户邮箱" prop="customerEmail">
        <el-input
          v-model="queryParams.customerEmail"
          placeholder="请输入客户邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单日期">
        <el-date-picker
          v-model="daterangeOrderDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fiscale:order:add']"
        >手动补录</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fiscale:order:export']"
        >导出Excel</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleQuery"
        >刷新</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 批量操作工具栏 -->
    <el-row :gutter="10" class="mb8" v-show="!multiple">
      <el-col :span="24">
        <el-alert
          :title="`已选择 ${multipleSelection.length} 项`"
          type="info"
          show-icon
          :closable="false"
        >
          <template slot="title">
            <span>已选择 {{ multipleSelection.length }} 项</span>
            <el-button-group style="margin-left: 20px;">
              <el-button 
                type="primary" 
                size="mini" 
                @click="handleBatchGenerateCustoms"
                v-hasPermi="['fiscale:order:customs']"
              >生成报关单</el-button>
              <el-button 
                type="warning" 
                size="mini" 
                @click="handleBatchUpdateStatus"
                v-hasPermi="['fiscale:order:edit']"
              >批量更新状态</el-button>
            </el-button-group>
          </template>
        </el-alert>
      </el-col>
    </el-row>

    <!-- 订单列表表格 -->
    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderNo" width="140" />
      <el-table-column label="平台订单号" align="center" prop="platformOrderNo" width="140" />
      <el-table-column label="平台类型" align="center" prop="platformType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_platform_type" :value="scope.row.platformType"/>
        </template>
      </el-table-column>
      <el-table-column label="客户信息" align="center" width="180">
        <template slot-scope="scope">
          <div>{{ scope.row.customerName }}</div>
          <div style="font-size: 12px; color: #999;">{{ scope.row.customerEmail }}</div>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="报关状态" align="center" prop="customsStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_customs_status" :value="scope.row.customsStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" prop="totalAmount" width="120">
        <template slot-scope="scope">
          {{ scope.row.currency }} {{ scope.row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column label="订单日期" align="center" prop="orderDate" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物流跟踪号" align="center" prop="trackingNumber" width="140" />
      <el-table-column label="手动补录" align="center" prop="isManual" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isManual == 1" type="warning">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['fiscale:order:detail']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fiscale:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fiscale:order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder, batchUpdateOrderStatus, batchUpdateCustomsStatus } from "@/api/fiscale/order";

export default {
  name: "Order",
  dicts: ['fiscale_platform_type', 'fiscale_order_status', 'fiscale_customs_status', 'fiscale_payment_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理表格数据
      orderList: [],
      // 多选数据
      multipleSelection: [],
      // 订单日期时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        platformOrderNo: null,
        platformType: null,
        platformConfigId: null,
        customerName: null,
        customerEmail: null,
        orderStatus: null,
        customsStatus: null,
        orderDate: null,
        beginOrderDate: null,
        endOrderDate: null
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeOrderDate && '' != this.daterangeOrderDate) {
        this.queryParams.params["beginOrderDate"] = this.daterangeOrderDate[0];
        this.queryParams.params["endOrderDate"] = this.daterangeOrderDate[1];
      }
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.multipleSelection = selection
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push('/fiscale/order/add');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const orderId = row.orderId || this.ids
      this.$router.push('/fiscale/order/edit/' + orderId);
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const orderId = row.orderId;
      this.$router.push('/fiscale/order/detail/' + orderId);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fiscale/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    /** 批量生成报关单 */
    handleBatchGenerateCustoms() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要生成报关单的订单");
        return;
      }
      this.$modal.confirm('是否确认为选中的 ' + this.ids.length + ' 个订单生成报关单？').then(() => {
        // 跳转到报关单生成页面，并传递选中的订单ID
        this.$router.push({
          path: '/fiscale/customs/declaration/create',
          query: { orderIds: this.ids.join(',') }
        });
      }).catch(() => {});
    },
    /** 批量更新状态 */
    handleBatchUpdateStatus() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要更新状态的订单");
        return;
      }
      
      this.$prompt('请输入新的订单状态', '批量更新状态', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(pending|confirmed|shipped|delivered|cancelled)$/,
        inputErrorMessage: '状态格式不正确，请输入：pending, confirmed, shipped, delivered, cancelled 之一'
      }).then(({ value }) => {
        const params = {
          orderIds: this.ids,
          orderStatus: value
        };
        batchUpdateOrderStatus(params).then(() => {
          this.getList();
          this.$modal.msgSuccess("更新成功");
        });
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>